<template>
    <div class="page-wrapper">
        <BreadMenu />
        <div style="height:96%; background:#fff; padding:var(--mPadding); ">
			<div style="padding-bottom:var(--mPadding); display:flex; justify-content: flex-end;">
                <div class="flex-btn opacity" @click="handleExport">
			    	<img :src="Icon" />
                    <span>导出</span>
			    </div>
            </div>    
            <el-scrollbar height="94%">
                <TableWrapper 
                    :hasControls="false" 
                    :sourceData="tableData" 
                    :column="column" 
                    :hasBorder="true" 
                    :hasPagination="false" 
                    :noPadding="true" 
                    :combineMethod="handleCombine" 
                    :cellStyle="setCellStyle"
                    @cell-click="handleCellClick"
                />
                <TableWrapper 
                    :hasControls="false" 
                    :sourceData="correctionList" 
                    :column="column2" 
                    :hasBorder="true" 
                    :hasPagination="false"
                    :noPadding="true" 
                    :combineMethod="handleCombine2"
                    @row-click="handleRowClick"
                />
            </el-scrollbar>
        </div>   
	</div> 
</template>

<script setup>
    import { watch, ref, reactive, onMounted, h } from 'vue';
    import { useRouter, useRoute } from 'vue-router';
    import { getTaskInspection, getTaskResult } from '@/api/task.js'; 
    import { useGlobalStore } from '@/stores/global';
    import { getCorrectionList  } from '@/api/correction.js';
    import BreadMenu from '@/components/BreadMenu.vue';
    import { ElMessage } from 'element-plus';
	import TableWrapper from '@/components/TableWrapper/index.vue';
    import { createSheet, downloadExcel } from '@/utils/excel.js';
    import Icon from '@/assets/icon-export.png';

    const global = useGlobalStore();
    const router = useRouter();
    const route = useRoute();
    const code = ref('');
    const tableData = ref([]);
    const correctionList = ref([]);
    const merges = [];
    const merges2 = [];
    const column = [
        { label:'巡检对象', prop:'targetName', width:'10%'},
        { label:'巡检项名称', prop:'itemName', width:'15%' },
        { label:'标准与要求', prop:'itemNormAndDemand', width:'35%' },
        { label:'检查方法及工具', prop:'checkWayAndTool', width:'20%' },
        { label:'巡检周期', prop:'cycleName', width:'10%' },
        // 1待处理;0不通过(需整改);3通过"
        { label:'巡检结果', prop:'checkResult', width:'10%', hasTpl:true, render:(row, index, scope)=>{
            const str = typeof row.checkResult === 'string' ? row.checkResult : Number(row.checkResult) === 3 ? '√' : '×';
            return { com:h('span', null, str), val:str };
        }}
    ]; 	
   
    const column2 = [
        { label:'', width:'5%', hasTpl:true, render:row=>({ com:h('span', null, '整改记录'), val:'整改记录' })},
        { label:'记录时间', width:'10%', hasTpl:true, render:row=>{ 
            let str = row.createTime ? row.createTime.replace('T', ' ').slice(0, row.createTime.length - 3): '--';
            return { com:h('div', null, str), val:str };
        }},
        { label:'巡检对象', prop:'targetName', width:'10%'},
        { label:'巡检项名称', prop:'itemName', width:'16%' },
        { label:'问题描述', prop:'problemDescription', width:'24%' },
        { label:'巡检人',  width:'5%', prop:'inspectionUser' },
        { label:'处理时间', width:'10%', hasTpl:true, render:row=>{ 
            let str = row.rectifyTime ? row.rectifyTime.replace('T', ' ').slice(0, row.rectifyTime.length - 3): '--';
            return { com:h('div', null, str), val:str }
        }},
        { label:'处理结果', width:'10%', prop:'rectifyStatus', hasTpl:true, render:row=>{
            let obj = global.correctionStatusMaps[row.rectifyStatus] ;
            let str = obj ? obj.text : '--';
            return { com:h('div', null, str ), val:str };
        }},
        { label:'处理人', width:'5%', prop:'rectifyUser' }
    ]
    function handleCombine({ row, column, rowIndex, columnIndex }){
        // console.log('row...', row);
        // console.log('column...', column);
        // console.log('rowIndex...', rowIndex);
        // console.log('columnIndex...', columnIndex);
        if ( columnIndex === 0 ) {
            if ( rowIndex === 0 ) {
                let obj = {
                    rowspan:tableData.value.length,
                    colspan:1
                }
                merges.push({ ...obj, rowIndex, columnIndex });
                return obj;
            } else {
                return {
                    rowspan:0,
                    colspan:0
                }
            }
        } 
        if ( rowIndex === tableData.value.length - 1 ){
            if ( columnIndex === 1 ) {              
                let obj = {
                    rowspan:1,
                    colspan:3
                }
                merges.push({ ...obj, rowIndex, columnIndex });
                return obj;
            } else if ( columnIndex === 2 || columnIndex === 3  ){
                return { rowspan:0, colspan:0 }
            }
        } 
    }  
    function setCellStyle({ row, column, rowIndex, columnIndex }){
        if ( rowIndex === tableData.value.length - 1 ) {
            if ( columnIndex === 1 ) {
                return { textAlign:'center', color:'#000', fontWeight:'bold' }
            }
        } 
    }
    function handleCombine2({ row, column, rowIndex, columnIndex }){
        if ( columnIndex === 0 ) {
            if ( rowIndex === 0 ) {  
                let obj = {
                    rowspan:correctionList.value.length,
                    colspan:1
                }         
                merges2.push({ ...obj, rowIndex, columnIndex });
                return obj;
            } else {
                return { rowspan:0, colspan:0 }
            }
        }
    }
    function handleRowClick(row){
        router.push({ path:'/correction', query:{ id:row.rectifyId  }})
    }
    function handleCellClick(row){
        router.push({ path:'/inspectionObject/inspectionHistory', query:{ id:row.targetId }})
    }
    function handleExport(){
        if ( tableData.value.length ) { 
            downloadExcel([
                { raw:createSheet(column, tableData.value, merges), sheetName:'巡检结果' }, 
                { raw:createSheet(column2, correctionList.value, merges2 ), sheetName:'整改记录' } 
            ], '任务执行结果');
        } else {
            ElMessage({
                type:'info',
                message:'数据源为空'
            })
        }
    }
    const fetchTaskResult = ()=>{
		getTaskResult({ missionCode:code.value })
		.then(res=>{
			if ( res.data.code === 200 ){
                let arr = res.data.data['inspectionMissionItemVOList'];
                if ( arr && arr.length ){
                    arr.push({ cycleName:'巡检人', checkResult:'张三', itemName:'说明：巡检正常 “√”、异常 “×”' })
                    tableData.value = arr;
                }
                if ( res.data.data['整改登记']) {
                    correctionList.value = res.data.data['整改登记'];
                } else {
                    correctionList.value = [{}, {}, {}, {}];
                }
			}
		})
	};
    onMounted(()=>{
        if ( route.query.code) {
            code.value = route.query.code;
            fetchTaskResult();
        }
    })
</script>

